﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Web;
using SHJunketingBLL;
using SHJunketingModel;

public partial class Admin_UserContent : System.Web.UI.Page
{
    int totle1 = 0;
    int totle2 = 0;

    public string startTime = "";
    public string endTime = "";
    public int intTime = 0;

    public string yuyuetime = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (!IsPostBack)
        {
            
            if (Session["userid"] != null)
            {
                string userId = Session["userid"].ToString();
                string sql = "select * from users where userid = '" + userId + "'";
                DataTable table = DBHelper.GetDataSet(sql);
                ViewState["UserTable"] = table;
                if (table.Rows.Count > 0)
                {
                    lblUserLogin.Text = table.Rows[0]["userlogin"].ToString();
                    if (table.Rows[0]["UserSex"].ToString().Equals("男"))
                    {
                        lblName.Text = "Mr."+table.Rows[0]["UserName"].ToString();
                    }
                    else 
                    {
                        lblName.Text = "Ms." + table.Rows[0]["UserName"].ToString();
                    }
                    lblUserIDCard.Text = table.Rows[0]["UserIDCard"].ToString();
                    lblUserAge.Text = table.Rows[0]["UserAge"].ToString();
                    lblUserSex.Text = table.Rows[0]["UserSex"].ToString();
                    lblMarriage.Text = table.Rows[0]["Marriage"].ToString();
                    lblHandsetNumber.Text = table.Rows[0]["HandsetNumber"].ToString();
                    lblTelephoneNumber.Text = table.Rows[0]["TelephoneNumber"].ToString();
                    lblUserEmail.Text = table.Rows[0]["UserEmail"].ToString();
                    lbllanguage.Text = table.Rows[0]["language"].ToString();



                    //修改信息
                    txtUserLogin.Text = table.Rows[0]["userlogin"].ToString();
                    txtUserIDCard.Text = table.Rows[0]["UserIDCard"].ToString();
                    txtAge.Text = table.Rows[0]["UserAge"].ToString();
                    //rdoSex.SelectedValue = table.Rows[0]["UserSex"].ToString();
                    if (table.Rows[0]["UserSex"].ToString().Equals(this.rdoMan.Text))//男 
                    {
                        this.rdoMan.Checked = true;
                    }
                    else
                    {
                        this.rdoWomen.Checked = true;
                    }
                    //RadioButtonList1.SelectedValue = table.Rows[0]["Marriage"].ToString();
                    if (table.Rows[0]["Marriage"].ToString().Equals(this.rdoHun.Text))
                    {
                        this.rdoHun.Checked = true;
                    }
                    else
                    {
                        this.rdoNoHun.Checked = true;
                    }
                    TextBox3.Text = table.Rows[0]["HandsetNumber"].ToString();
                    TextBox4.Text = table.Rows[0]["TelephoneNumber"].ToString();
                    TextBox5.Text = table.Rows[0]["UserEmail"].ToString();
                    //RadioButtonList2.SelectedValue = table.Rows[0]["language"].ToString();
                    if (table.Rows[0]["language"].ToString().Equals(this.rodlanguage.Text))
                    {
                        this.rodlanguage.Checked = true;
                    }
                    else
                    {
                        this.rodlanguageEnglish.Checked = true;
                    }
                    txtpwd.Text = table.Rows[0]["UserPwd"].ToString();

                    //保存密码和ID

                    ViewState["userId"] = table.Rows[0]["UserId"];
                    ViewState["pass"] = table.Rows[0]["UserPwd"];

                    intTime = int.Parse(table.Rows[0]["logtime"].ToString());

                    yuyuetime =table.Rows[0]["yuyuetime"].ToString();
                }
                
                LoadJigou();//加载医院下拉列表

                LoadTimeFromLimit();//加载时间下拉列表

                getAgency();//验证预约信息

                getTime();//获得预约人数

                DataTable dt = HospitalBll.GetHospitalInfo(ddljigou.SelectedValue);
                //hos.Text = dt.Rows[0]["jieshao"].ToString();
            }
            else 
            {
                Web.CommFun.Show_Msg("信息丢失，请重新登录", "index.aspx");
            }
            if (intTime == 0)
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>Editblock();</script>");

            }

        }

        
    }


    private DataTable GetAllJigou()
    {
        DataTable dt = HospitalBll.GetAllJigou();
        return dt;
    }

    //加载医疗机构
    public DataTable dt = new DataTable();

    protected void LoadJigou()
    {
        dt = LimitBll.GetAllLimitHospital(yuyuetime);

        this.ddljigou.Items.Clear();      //清除DropDownList中的内容


        if (dt == null || dt.Rows.Count == 0)
        {

            this.ddlTime.Items.Add(new ListItem("没有添加预约机构", ""));

        }
        else
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                this.ddljigou.Items.Add(new ListItem(dt.Rows[i]["hospital"].ToString(), dt.Rows[i]["hospital"].ToString()));
            }
        }

        if (ddljigou.Items.Count > 0)
        {
            ddljigou.SelectedIndex = 0;
        }
    }

   

    //修改用户资料
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        if (lblSurplus.Text == lblTotle.Text)
        {
            Web.CommFun.Show_Msg("预约人数已满，请选其他日期或医院！");
            return;
        }

        string userSex = string.Empty;
        string marriage = string.Empty;
        string language = string.Empty;

        if (this.rdoMan.Checked) 
        {
            userSex = this.rdoMan.Text;
        }
        else if (rdoWomen.Checked) 
        {
            userSex = this.rdoWomen.Text;
        }
        if (rdoHun.Checked)
        {
            marriage = this.rdoHun.Text;
        }
        else if(rdoNoHun.Checked)
        {
            marriage = rdoNoHun.Text;
        }
        if (rodlanguage.Checked) 
        {
            language = rodlanguage.Text;
        }
        else if (rodlanguageEnglish.Checked) 
        {
            language = rodlanguageEnglish.Text;
        }

        string sql = string.Empty;
        if (txtpwd.Text.Trim() != "") //重新输入密码
        {
            sql =
               "UPDATE users " +
               "SET " +
                   "UserLogin = '" + txtUserLogin.Text.Trim() + "', " +
                   "UserPwd = '" + txtpwd.Text.Trim() + "', " +
                   "UserIDCard = '" + txtUserIDCard.Text.Trim() + "'," +
                   "UserAge = '" + txtAge.Text.Trim() + "'," +
                   "UserSex = '" + userSex + "'," +
                   "Marriage  = '" + marriage + "'," +
                   "HandsetNumber = '" + TextBox3.Text.Trim() + "'," +
                   "TelephoneNumber = '" + TextBox4.Text.Trim() + "'," +
                   "UserEmail = '" + TextBox5.Text.Trim() + "'," +
                   "logtime=1," +
                   "language  = '" + language + "'" +

               " WHERE UserID = '" + ViewState["userId"].ToString() + "'";
        }
        else 
        {
             sql =
                "UPDATE users " +
                "SET " +
                    "UserLogin = '" + txtUserLogin.Text.Trim() + "', " +
                    "UserIDCard = '" + txtUserIDCard.Text.Trim() + "'," +
                    "UserAge = '" + txtAge.Text.Trim() + "'," +
                    "UserSex = '" + userSex + "'," +
                    "Marriage  = '" + marriage + "'," +
                    "HandsetNumber = '" + TextBox3.Text.Trim() + "'," +
                    "TelephoneNumber = '" + TextBox4.Text.Trim() + "'," +
                    "UserEmail = '" + TextBox5.Text.Trim() + "'," +
                    "logtime=1," +
                    "language  = '" + language + "'" +

                " WHERE UserID = '" + ViewState["userId"].ToString() + "'";
        }

       

        int resutl = DBHelper.ExecuteCommand(sql);
        if (resutl > 0)
            Web.CommFun.Show_Msg("修改个人信息成功！", "UserContent.aspx");
        else
            Web.CommFun.Show_Msg("修改个人信息失败，退出再次登录！", "UserContent.aspx");
    }
    //退出
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        Session["userid"] = null;
        Web.CommFun.Show_Msg("退出成功，请再次登录！", "index.aspx");
    }
    //预约体检
    protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
    {
        if (ViewState["userId"] != null)
        {
            DateTime time = DateTime.Now;
            //DateTime ddltime = DateTime.Parse(ddlTime.SelectedValue);
            DateTime ddltime = DateTime.Parse(ddlTime.SelectedItem.Text);
            TimeSpan ts = ddltime - time;  //得到时间差
            if (ts.TotalDays > 1)
            {

                DataTable userTable = (DataTable)ViewState["UserTable"];//取出用户信息

                if (userTable.Rows[0]["userSex"].ToString() == "" || userTable.Rows[0]["userSex"] == null)
                {
                    Web.CommFun.Show_Msg("您的性别为空，请修改后在预约！");

                }
                else if (userTable.Rows[0]["userage"].ToString() == "" || userTable.Rows[0]["userage"] == null)
                {
                    Web.CommFun.Show_Msg("您的年龄为空，请修改后在预约！");

                }
                else if (userTable.Rows[0]["Marriage"].ToString() == "" || userTable.Rows[0]["Marriage"] == null)
                {
                    Web.CommFun.Show_Msg("您的婚否为空，请修改后在预约！");

                }
                else
                {
                    string address = null;
                    string num = null;

                    if (ddljigou.SelectedItem.Text != "")
                    {
                        //address = "上海市浦东新区浦东南路256号华夏银行大厦3楼";
                        address = ddljigou.SelectedItem.Text;
                        num = lblTotle.Text;
                    }

                    string sql1 = "select * from MedicalAppointment where UserID ='" + ViewState["userId"] + "'";
                    DataTable table1 = DBHelper.GetDataSet(sql1);

                    string setMeal = string.Empty;//体检套餐
                    string sex = userTable.Rows[0]["userSex"].ToString();//性别
                    int age = Convert.ToInt32(userTable.Rows[0]["userAge"].ToString());//年龄
                    string marriage = userTable.Rows[0]["Marriage"].ToString();

                    if ( sex.Equals("男"))
                    {
                        setMeal = "套餐-男";
                    }
                    if (sex.Equals("女") && marriage.Equals("未婚"))
                    {
                        setMeal = "套餐-女-未婚";
                    }
                    if (age < 40 && sex.Equals("女") && marriage.Equals("已婚"))
                    {
                        setMeal = "套餐-女-已婚";
                    }

                    if (table1.Rows.Count > 0) //有预约体检
                    {
                        string sql = "update MedicalAppointment set ReservationTime = '" + this.ddlTime.SelectedItem.Text + "',SetMeal='" + setMeal + "',AgencyName='"
                            + ddljigou.SelectedValue + "',AgencyAddress='" + address + "',ReservationNum='" + num + "',BookingStatus=0 where userid = '" + ViewState["userId"] + "'";
                        DBHelper.ExecuteCommand(sql);
                    }
                    else
                    {
                        string sql = "insert into MedicalAppointment values('" + ViewState["userId"].ToString() + "','" + this.ddlTime.SelectedItem.Text + "','" + setMeal + "','"
                            + ddljigou.SelectedValue + "','" + address + "','2011年7月17-8月1','" + num + "','0')";
                        Web.DBHelper.GetScalar(sql);
                    }
                    Web.CommFun.Show_Msg("预约成功！", "UserContent.aspx");
                }
            }
            else 
            {
                Web.CommFun.Show_Msg("请提前两个工作日进行预约！", "UserContent.aspx");
            }
        }
    }

    public void getAgency() 
    {
        try
        {


            ViewState["userid"] = Session["userid"].ToString();
            string sql = "select * from MedicalAppointment where userid='" + ViewState["userid"].ToString() + "' and BookingStatus != 1";
            DataTable tableSql = DBHelper.GetDataSet(sql);


            if (tableSql.Rows.Count > 0) //验证是否预约
            {
                if (tableSql.Rows.Count > 0)
                {
                    DateTime timeNows = DateTime.Parse(tableSql.Rows[0]["ReservationTime"].ToString());//员工预约时间
                    DateTime timeNow = DateTime.Now;
                    //int time1 = int.Parse((timeNows - timeNow).ToString());
                    TimeSpan ts = timeNows - timeNow;
                    if (ts.TotalDays < 5)
                    {
                        this.ddljigou.Enabled = false;
                        this.ddlTime.Enabled = false;
                        ImageButton3.Enabled = false;
                    }

                    this.lblStatus.Text = "已预约";

                }
                if (tableSql.Rows[0]["BookingStatus"].ToString().Equals("2"))
                {
                    this.ddljigou.Enabled = false;
                    this.ddlTime.Enabled = false;
                    ImageButton3.Enabled = false;
                    this.lblStatus.Text = "已体检";

                }
                this.ddljigou.SelectedValue = tableSql.Rows[0]["AgencyName"].ToString();
                this.ddlTime.SelectedValue = DateTime.Parse(tableSql.Rows[0]["ReservationTime"].ToString()).ToString("yyyy-MM-dd");
                //this.ddlTime.SelectedValue = tableSql.Rows[0]["ReservationTime"].ToString();
            }
        }
        catch { }
    }

    protected void ddljigou_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddljigou.SelectedValue != "")
        {
            LoadTimeFromLimit();
        }

        DataTable dt=HospitalBll.GetHospitalInfo(ddljigou.SelectedValue);
        //hos.Text = dt.Rows[0]["jieshao"].ToString();
    }

    public void  LoadTimeFromLimit()
    {
        DataTable dt = new DataTable();


        string hospital = ddljigou.SelectedValue;

       dt= LimitBll.GetTimeByHospital(hospital);

       if (dt == null || dt.Rows.Count == 0)
       {


           this.ddlTime.Items.Add(new ListItem("没有添加预约日期", ""));

       }
       else 
       {

           for (int i = 0; i < dt.Rows.Count; i++)
           {
               this.ddlTime.Items.Add(new ListItem(dt.Rows[i]["date"].ToString(), dt.Rows[i]["id"].ToString()));
           }
       
       }

       if (ddlTime.Items.Count > 0)
       {
           ddlTime.SelectedIndex = 0;
       }
    }


    private void LoadTime()
    {
        int id = 0;
        Hospital hos = new Hospital();

        try
        {
            id = int.Parse(ddljigou.SelectedValue);
            ddlTime.Items.Clear();

            hos = GetTime(id);


            totle1 = hos.Yuyueshangxian1;
            totle2 = hos.Yuyueshangxian2;

            C_YuyueType yuyue = C_YuyueTypeManage.GetYuyueTypeByID(hos.Yuyuefenleiid);

            DateTime start = new DateTime();
            startTime = yuyue.Starttime;
            endTime = yuyue.Endtime;
            start = DateTime.Parse(yuyue.Starttime);

            DateTime end = new DateTime();

            end = DateTime.Parse(yuyue.Endtime);

            TimeSpan ts = end - start;
            int sub = ts.Days + 1;     //sub就是两天相差的天数

            ListItem item = new ListItem();

            for (int i = 0; i < sub; i++)
            {
                this.ddlTime.Items.Add(new ListItem(start.AddDays(i).ToString("yyyy-MM-dd"), start.AddDays(i).ToString("yyyy-MM-dd")));
            }

            if (ddlTime.Items.Count > 0)
            {
                ddlTime.SelectedValue = start.ToString("yyyy-MM-dd");
            }
        }
        catch { }
    }

    public Hospital GetTime(int id)
    {
        Hospital hos = new Hospital();

        try
        {
            hos = HospitalBll.GetJigouById(id);
        }
        catch { }

        return hos;
    }

  

    protected void ddlTime_SelectedIndexChanged(object sender, EventArgs e)
    {
        //getTime();
        getAgency();//验证预约信息

        getTime();//获得预约人数
    }

    private void getTime()
    {
        try
        {
            string time = this.ddlTime.SelectedValue;  //获得时间
            string agencyName = this.ddljigou.SelectedValue; //机构名称

            if (ddlTime.SelectedValue == "" || ddljigou.SelectedValue == "")
            {
                lblSurplus.Text = "无";
                lblTotle.Text = "无";
                ImageButton3.Visible = false;
            }
            else
            {

                Limit limit = LimitBll.GetLimitById(int.Parse(time));

                lblTotle.Text = limit.Shangxian.ToString();

                string sql = "select COUNT(*)as counts from MedicalAppointment where ReservationTime ='" + this.ddlTime.SelectedItem.Text + " 0:00:00" + "' and AgencyName = '" + agencyName + "' and BookingStatus!=1";
               
                DataTable tableTime = DBHelper.GetDataSet(sql);

                lblSurplus.Text = tableTime.Rows[0]["counts"].ToString();

                if (int.Parse(tableTime.Rows[0]["counts"].ToString()) >= limit.Shangxian) //人数超过上线
                {
                    ImageButton3.Enabled = false;
                    this.lblZ.Text = "预约人数已满";
                }
            }
        }
        catch 
        { 
        
        }
    }
}
